﻿using PeshoMVC.Models;
using PeshoMVC.MyHelpers;
using System.Web.Mvc;
using System.Web.Security;

namespace PeshoMVC.Controllers
{
    public class AccountController : Controller
    {
        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                // search if this user name or email exist
                var user = Membership.GetUser(model.UserName);
                var userByMail = Membership.GetUserNameByEmail(model.Email);

                if (user == null && userByMail == null)
                {
                    var newUser = Membership.CreateUser(model.UserName, model.Password, model.Email);

                    Roles.AddUserToRole(newUser.UserName, "user");

                    // write userId in profile table
                    Data.GetId(model.UserName);

                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ViewBag.Error = "The user name or e-mail already exist!";
                    return View(model);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.RedirectFromLoginPage(model.UserName, false);
                }

                ViewBag.Error = "Wrong user name or password!";
                return View(model);
            }

            // If we got this far, something failed, redisplay form
            ViewBag.Error = "Theare is some error.Try again";
            return View(model);
        }

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }
    }
}